const httpUtils = require('../../../utils/httpUtil')
Page({
  data: {
    myGroups: [],
    selectedDeviceIds: [],
    selectedDeviceIdsCache: [],
    selectedTemplateIndex: 0,
    audioTemplate: [
      // {
      //   id: 0,
      //   type: 0,
      //   title: '一级告警',
      //   content: '山洪撤离',
      //   selected: true,
      // },
      // {
      //   id: 1,
      //   type: 1,
      //   title: '二级告警',
      //   content: '山洪撤离',
      //   selected: false,
      // },
      // {
      //   id: 2,
      //   type: 1,
      //   title: '三级告警',
      //   content: '山洪撤离',
      //   selected: false,
      // },
    ],
    calling: false,
    measurementStationNo: null,
  },

  onLoad(options) {
    if (options.measurementStationNo != null) {
      this.setData({
        measurementStationNo: options.measurementStationNo
      });
    }
  },

  onShow() {
    this.getAudioTemplate();
  },

  onUnload() {
    if (this.data.calling) {
      this.stopWavCall();
    }
  },

  onSelectionChange(e) {
    console.log('Selection changed in page:', e.detail.selectedDeviceIds);
    this.setData({
      selectedDeviceIds: e.detail.selectedDeviceIds
    });
  },

  // 如果需要主动获取选中列表
  getSelectedDevicesFromComponent() {
    const selectorComponent = this.selectComponent('#groupSelector');
    if (selectorComponent) {
      const selectedIds = selectorComponent.getSelectedDeviceIds();
      console.log('Got selected IDs:', selectedIds);
      // ... 处理获取到的 ID 列表
    }
  },

  selectTemplate(e) {
    if (this.data.calling) {
      wx.showToast({
        title: '请先停止上一个喊话',
        icon: 'error',
      });
      return;
    }

    const tappedIndex = e.currentTarget.dataset.index;
    console.log('选中：'+tappedIndex);
    for (const idx in this.data.audioTemplate) {
      if (idx == tappedIndex) {
        this.data.audioTemplate[idx].selected = true;
      } else {
        this.data.audioTemplate[idx].selected = false;
      }
    }
    this.setData({
      selectedTemplateIndex: tappedIndex,
      audioTemplate: this.data.audioTemplate
    })
  },

  getAudioTemplate() {
    httpUtils.request({
      'method': 'GET',
      'url': '/prod-api/interface/getModelList',
    }).then(res=>{
      this.data.audioTemplate = [];
      let result = new Map(Object.entries(res.data));
      for (let templates of result.values()) {
        if (templates.length == 0) {
          continue;
        }
        templates.sort((a, b) => {
          if (a.grade > b.grade) {
            return -1;
          } else if (a.grade < b.grade) {
            return 1;
          } else {
            return 0;
          }
        });
        let arr = templates.map(template=>{
          return {
            id: template.id,
            type: template.type,
            title: template.publishTheme,
            content: template.remark,
            selected: false
          }
        });
        this.setData({
          audioTemplate: this.data.audioTemplate.concat(arr)
        });
      }

      if (this.data.audioTemplate.length > 0) {
        this.data.audioTemplate[0].selected = true;
        this.setData({
          audioTemplate: this.data.audioTemplate
        });
      }
    });
  },
  
  wavCall() {
    if (this.data.selectedDeviceIds.length < 1) {
      wx.showToast({
        title: '请至少选择一个设备',
        icon: 'error'
      })
      return;
    } 

    console.log('选中设备：'+this.data.selectedDeviceIds);
    console.log('选中模版：'+this.data.audioTemplate[this.data.selectedTemplateIndex].title);

    httpUtils.request({
      'method': 'POST',
      'url': '/prod-api/interface/sendSms',
      'showLoading': true,
      'messages': '喊话中',
      'data': {
        'numbers': this.data.selectedDeviceIds,
        'id': this.data.audioTemplate[this.data.selectedTemplateIndex].id,
        'measurementStationNo': this.data.measurementStationNo,
        'type': this.data.calling ? 2 : 1,
      }
    }).then(res=>{
      if (res.data.code == 200) {
        // this.setData({
        //   calling: !this.data.calling,
        //   selectedDeviceIdsCache: this.data.selectedDeviceIds,
        // })
        const url = '/pages/call/answer/answer?callId='+res.data.msg+'&callType=0&callContent='+this.data.audioTemplate[this.data.selectedTemplateIndex].content+'&callDeviceIds='+this.data.selectedDeviceIds;
        console.log('跳转url：'+url);
        wx.navigateTo({
          url: url,
        });

      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'error'
        })
      }
      
    });
  },

  stopWavCall() {
    httpUtils.request({
      'method': 'POST',
      'url': '/prod-api/interface/sendSms',
      'showLoading': true,
      'messages': '停止喊话',
      'data': {
        'numbers': this.data.selectedDeviceIdsCache,
        'type': 2,
      }
    }).then(res=>{
      this.setData({
        selectedDeviceIdsCache: [],
        calling: false,
      })
    });
  },
});